package cn.com.zero.common.auth.security.service;

import cn.com.zero.api.auth.util.UserCacheKeyUtil;
import cn.com.zero.base.util.RedisUtil;
import cn.com.zero.common.auth.security.po.AuthUserPO;
import cn.com.zero.common.auth.security.vo.UserDetailsVO;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;

/**
 * @author xiongxj
 * @version 1.0.0
 * @Description 自定义的抽象加载用户信息service类
 * @createTime 2023/3/21 9:48
 */
public abstract class AbstractUserDetailsService implements UserDetailsService {
    protected AbstractLoginAuthenticationService loginAuthenticationService;
    protected RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String userPrincipal) throws UsernameNotFoundException {
        AuthUserPO authUserPO = getUser(userPrincipal);
        if (null == authUserPO) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDetailsVO userDetailsVO = new UserDetailsVO();
        userDetailsVO.setUserInfo(authUserPO);
        // 查看用户是否已被锁定
        Object object = redisUtil.getObject(UserCacheKeyUtil.getLockedUserCacheKey(loginAuthenticationService.getAuthenticationSide(), authUserPO.getUserId()));
        if (null == object) {
            // 说明用户未被锁定
            userDetailsVO.setAccountNonLocked(true);
        }
        return userDetailsVO;
    }

    /**
     * 根据手机号或者用户名称获取用户信息
     *
     * @param userPrincipal 用户身份的唯一标识，如手机号、用户名称等。
     * @return 用户信息
     */
    protected abstract AuthUserPO getUser(String userPrincipal);

    @Resource
    public void setLoginAuthenticationService(AbstractLoginAuthenticationService loginAuthenticationService) {
        this.loginAuthenticationService = loginAuthenticationService;
    }

    @Resource
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }
}
